package utility

import (
	"math/rand"
	"os"
	"os/exec"
	"regexp"
	"strings"
)

// SplitString 字符串分割
func SplitString(str string, delimiters []string) []string {
	if len(delimiters) == 0 {
		return []string{str}
	}

	arr := []string{str}
	for _, delimiter := range delimiters {
		var newArr []string
		for _, item := range arr {
			newArr = append(newArr, strings.Split(item, delimiter)...)
		}
		arr = newArr
	}
	return arr
}

// Filter 过滤
func Filter(slice []string, function func(string) bool) []string {
	var result []string
	for _, str := range slice {
		if function(str) {
			result = append(result, str)
		}
	}
	return result
}

// RandStringBytes 随机字符串
func RandStringBytes(n int) string {
	const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	b := make([]byte, n)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}
	return string(b)
}

// IsZip 是否是zip文件
func IsZip(filename string) bool {
	return strings.HasSuffix(filename, ".zip")
}

// IsValidEmail 验证邮箱
func IsValidEmail(email string) (bool, error) {
	return regexp.MatchString(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`, email)
}

// IsValidPhone 验证手机号
func IsValidPhone(phone string) (bool, error) {
	return regexp.MatchString(`^1[3-9]\d{9}$`, phone)
}

type Node[T any] interface {
	ID() string
	ParentID() string
	GetChildren() []T
	SetChildren([]T)
}

// ArrayToTree 数组转树形结构
func ArrayToTree[T Node[T]](nodes []T) []T {
	nodeMap := make(map[string]T)
	for _, node := range nodes {
		nodeMap[node.ID()] = node
	}

	var roots []T
	for _, node := range nodes {
		if parent, ok := nodeMap[node.ParentID()]; ok {
			parent.SetChildren(append(parent.GetChildren(), node))
		} else {
			roots = append(roots, node)
		}
	}

	return roots
}

func ExecuteCommand(name string, args ...string) error {
	cmd := exec.Command(name, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func ReplaceSpaces(input string) string {
	// 使用正则表达式将多个空格替换为单个空格
	re := regexp.MustCompile(`\s+`)
	trimmed := re.ReplaceAllString(input, " ")

	// 将单个空格替换为 -
	result := strings.ReplaceAll(trimmed, " ", "-")
	return result
}
